import { Component, SecurityContext, ChangeDetectorRef } from '@angular/core';

import { Events, AlertController, App, List, ModalController, NavController, NavParams, ActionSheetController } from 'ionic-angular';
import { DomSanitizer } from '@angular/platform-browser';

import { DraftDetailService } from './detail.service';
import { EmpPage } from '../../task/detail/emp.component';
import { Config } from '../../../providers/config';
import { Common } from '../../../providers/common';

import { ContactChoosePage } from '../../contact/choose/choose.component';
import { Storage } from '@ionic/storage';
import _ from 'lodash';
import { FlowParmeter } from './flowParmeter.model';
import {DraftAddrModal} from "./addr.modal";
import {DraftIndustryInfoModal} from "./industryInfo.modal";
import {DraftCompanyCodeModal} from "./companyCode.modal";
import {MainPage} from "../../main/main.component";
import {TaskDetailService} from "../../task/detail/detail.service";
import * as moment from "moment";

/**
 * 出差明细entry类
 */
class ChuchaiEntry {
  constructor() {
    this.glbosid = "";
    this.bostitle = "";
    this.empid = "";
    this.starttime = "";
    this.endtime = "";
    this.gsname = "";
    this.gscode = "";
    this.remark = "";
    this.address = "";
    this.rescatg = "";
    this.indinf = "";
    this.rescatgname = "";
    this.indinfid = "";
    this.addressid = "";

  }

  glbosid: string;//关联出差申请单ID
  bostitle: string;//出差申请单标题
  empid: string;//用户ID
  starttime: string;//开始日期
  endtime: string;//结束日期
  gsname: string;//上市公司名称
  gscode: string;//公司ID
  remark: string;//备注
  address: string;//地点
  rescatg: string;//调研类别
  indinf: string;//行业信息
  rescatgname: string;//调研类别名称
  indinfid: string;//行业信息ID
  addressid: string;//地点ID
}


/**
 * TODO:
 * 1.考虑将setIsShowProperty，setDefSelectOption，setDefDateNode，changeNodePosition 放到服务端
 */
@Component({
  selector: 'page-draft-detail',
  templateUrl: './detail.html',
  providers: [DraftDetailService, FlowParmeter, TaskDetailService]
})
export class DraftDetailPage {
  _ = _;
  moa_page_name: any = "page-draft-detail";
  moa_page_explain: any = "";
  // 出差申请:ccsq,出勤变更:cqbg,公务外出:gwwc,请休假申请:qxjsq
  type;
  // 标题
  title = {
    "cjsq": "出境申请",
    "ccsq": "出差申请",
    "cqbg": "出勤变更",
    "gwwc": "公务外出",
    "qxjsq": "请休假申请",
    "xgipoxj": "新股IPO询价",
    "xgiposg": "新股IPO网上申购"
  }

  //新股IPO询价评价特殊处理
  ipoShowCondition = ["iszqfh", "objectiveassess", "reasonassess", "totalityassess"];

  changeToDate = ["InquiryStartDay", "wxsgDay"];

  //新股IPO询价评价placeholder
  ipoAssessPlaceholder:string = "";

  //新股IPO意见部文本框转成输出显示处理
  textareaToText = ["yjyyj", "tzmsyj", "jjjlyj", "tzjcxzyj", "zyjybidea", "bcyj", "jjkjbidea", "jlhqyj", "mshqyj", "fkgshyj", "tzzjshyj", "jyyyj", "yjyqryj"];

  //preLine = ["issuestotstock", "ipototstock", "webipototstock", "totnegcap", "minbuy", "maxbuy", "minnum", "minprice", "maxprice"];
  certiid = ["certiid", "CertiId"];

  // 文件信息带字段
  businessObjectDesList;
  // 流程信息
  workFlowParmeter;
  flowParmeter: FlowParmeter;

  loginid;
  //外出人员
  empnames = [];
  empnamesId = [];
  // 缓存通过组织树选择的人员
  // 结构如下：
  // [{
  //   empid:"A938493525",
  //   name:"冯镜蒯",
  //   orgid:"xtyfz",
  //   loginid:"fengjk",
  //   titleid:"ybyg"
  // },{}]
  defaultEmpByTree = [];

  defaltGwwcEmpByTree = [];

  businessTripDetail = {
    normal: [],
    survey: []
  };

  selectedAddr = [];
  // selectedCompanyCode = [];
  // selectedIndustryInfo = [];

  qyType = "2";

  detailEntry = [];
  leaveEntry: any[] = []
  leaveType: any[]

  ops = null;
  bosid = null;
  taskDetail = null;

  maxDate = "";

  showEntryEndTime = true;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public detailService: DraftDetailService,
    private navParams: NavParams,
    private actionSheetCtrl: ActionSheetController,
    public config: Config,
    public common: Common,
    public storage: Storage,
    private sanitizer: DomSanitizer,
    public events: Events,
    public taskDetailService: TaskDetailService,
    private changeDetectorRef:ChangeDetectorRef
  ) {
    this.type = this.navParams.get('type');
    this.moa_page_explain = this.title[this.type];

    this.ops = "insert";
    let nowDate = this.common.getNowFormatDate();
    let nowYear = parseInt(nowDate.substr(0, 4)) + 1;
    this.maxDate = _.toString(nowYear) + "-12" + "-31";
    this.loadData();
  }

  ionViewDidLoad() {
    // this.app.setTitle('DraftDetail');
  }

  addDetail() {
    _.forEach(this.detailEntry, detail => {
      detail.expand = false;
    });

    let newEntry = {
      expand: true,
      selectedAddr: [],
      selectedCompanyCode: null,
      selectedIndustryInfo: [],
      field: new ChuchaiEntry()
    };
    newEntry.field.bostitle = _.find(this.businessObjectDesList, {fieldid: "bostitle"})["fvalue"] + new Date().getTime();
    this.storage.get("userInfo").then(user => {
      console.log(user);
      newEntry.field.empid = user.empid;
    });
    // newEntry.field.BOSTITLE = _.find(this.businessObjectDesList, {fieldid: "bostitle"})["fvalue"];
    let ccresonField = _.find(this.businessObjectDesList, {fieldid: "ccreson"});
    switch (this.qyType) {
      case '1'://调研
        newEntry.field.starttime = this.common.getNowFormatDate();
        newEntry.field.endtime = this.common.getNowFormatDate();
        newEntry.field.rescatg = "1";
        newEntry.field.rescatgname = "上市公司调研";
        newEntry.field.remark = ccresonField["fvalue"];
        break;
      case '2'://一般出差
        newEntry.field.starttime = this.common.getNowFormatDate();
        newEntry.field.endtime = this.common.getNowFormatDate();
        newEntry.field.remark = ccresonField["fvalue"];
        break;
    }
    this.detailEntry.push(newEntry);
  }

  ccDetailDate(entry) {
    console.log("ccDetailDate", entry);
    if (new Date(entry.field.starttime.replace(/-/g, "/")) > new Date(entry.field.endtime.replace(/-/g, "/")) ) {
      this.timeAlert("开始日期不能大于结束日期");
      // entry.field.endtime = entry.field.starttime;
      // let index = _.findIndex(this.detailEntry, entry);
      entry.field.endtime = entry.field.starttime;
      this.changeDetectorRef.markForCheck();
      this.showEntryEndTime = false;
      setTimeout(() => {
        this.showEntryEndTime = true;
      }, 100);
      console.log(entry.field.endtime);
    }
  }

  removeDetail(entry) {
    _.remove(this.detailEntry, entry);
  }

  expandDetail(entry) {
    entry.expand = !entry.expand;
  }

  surveyTypeChange(entry) {
    switch (entry.field.rescatg) {
      case "1":
        entry.field.rescatgname = "上市公司调研";
        entry.field.indinf = "";
        entry.field.indinfid = "";
        break;
      case "2":
        entry.field.rescatgname = "行业调研";
        entry.field.gsname = "";
        entry.field.gscode = "";
        break;
      case "3":
        entry.field.rescatgname = "其它调研";
        entry.field.gsname = "";
        entry.field.gscode = "";
        entry.field.indinf = "";
        entry.field.indinfid = "";
        break;
    }
  }

  selectIndustryInfo(entry) {
    let profileModal = this.modalCtrl.create(DraftIndustryInfoModal, {
      selectedIndustryInfo: entry.selectedIndustryInfo
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        entry.selectedIndustryInfo = data;
        entry.field.indinf = _.toString(_.map(_.map(data, "entry"), "industry_name_level2"));
        entry.field.indinfid = _.toString(_.map(_.map(data, "entry"), "industry_code_level2"));
      }
    });
    profileModal.present();
  }

  selectCompanyCode(entry) {
    let profileModal = this.modalCtrl.create(DraftCompanyCodeModal, {
      selectedCompanyCode: entry.selectedCompanyCode
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        entry.selectedCompanyCode = data;
        entry.field.gsname = data.entry["SECURITIESID"];
        entry.field.gscode = data.entry["ID"];
      }
    });
    profileModal.present();
  }

  selectAddr(entry, type) {
    if (type == 0) {
      entry.selectedAddr = this.selectedAddr;
      console.log(entry.selectedAddr);
    }
    let profileModal = this.modalCtrl.create(DraftAddrModal, {
      selectedAddr: entry.selectedAddr
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        if (type == 0) {
          this.selectedAddr = data;
          entry.fvalue = _.toString( _.map(_.map(data, "entry"), "province_city") );
        } else {
          entry.selectedAddr = data;
          entry.field.address = _.toString( _.map(_.map(data, "entry"), "province_city") );
        }
      }
    });
    profileModal.present();
  }

  addLeave(): void {
	if (this.leaveEntry.length > 0) {
		this.leaveEntry.forEach((v: any) => {
			v.isShow = false;
		});
	}
    let entry: any = {
      mxid: "",
      qjtype: "",
      ksrq: "",
      jsrq: "",
      kssj: "",
      jssj: "",
      qjts: "",
      bzsm: "",
	  glbosid: "",
	  isShow: true
    };
    entry.ksrq = _.find(this.businessObjectDesList, {
      fieldid: "startdate"
    })["fvalue"];
    entry.jsrq = _.find(this.businessObjectDesList, {
      fieldid: "enddate"
    })["fvalue"];
    this.leaveEntry.push(entry);
  }

  removeLeave(i: number): void {
	//_.remove(this.leaveEntry, item);
	this.leaveEntry.splice(i, 1);
  }

  timeAlert(msg: string): void {
    let alert = this.alertCtrl.create({
      title: "温馨提示",
      subTitle: msg,
      buttons: ["确定"]
    });
    alert.present();
  }

  selectDateLimit(item: any, type: number): void {
    if (this.type === "cjsq") {
      let startDateVal: string = _.find(this.businessObjectDesList, {
          fieldid: "startdate"
        })["fvalue"],
        startTimeVal: string = _.find(this.businessObjectDesList, {
          fieldid: "startpoint"
        })["fvalue"],
        endDateVal: string = _.find(this.businessObjectDesList, {
          fieldid: "enddate"
        })["fvalue"],
        endTimeVal: string = _.find(this.businessObjectDesList, {
          fieldid: "endpoint"
        })["fvalue"];
      let startTime = startDateVal + " " + startTimeVal + ":00",
        endTime = endDateVal + " " + endTimeVal + ":00";
      if (type === 1 && item.ksrq + " " + item.kssj + ":00" < startTime) {
        setTimeout(() => {
          item.ksrq = _.find(this.businessObjectDesList, {
            fieldid: "startdate"
          })["fvalue"];
          item.kssj = "";
        }, 1000);
        this.timeAlert("开始时间不能小于起始时间");
        return;
      } else if (type === 2 && item.jsrq + " " + item.jssj + ":00" > endTime) {
        setTimeout(() => {
          item.jsrq = _.find(this.businessObjectDesList, {
            fieldid: "enddate"
          })["fvalue"];
          item.jssj = "";
        }, 1000);
        this.timeAlert("结束时间超出范围");
        return;
      } else if (type === 2 && item.ksrq + " " + item.kssj + ":00" > item.jsrq + " " + item.jssj + ":00") {
        setTimeout(() => {
          item.jsrq = _.find(this.businessObjectDesList, {
            fieldid: "enddate"
          })["fvalue"];
          item.jssj = "";
        }, 1000);
        this.timeAlert("结束时间不能小于开始时间");
        return;
      } else if (item.type !== "" && item.ksrq !== "" && item.kssj !== "" && item.jsrq !== "" && item.jssj !== "") {
		this.detailService.calcLeaveDays(item, this.leaveEntry, this.leaveType);
		let restdaysIndex: number = _.findIndex(this.businessObjectDesList, {
          fieldid: "restdays"
		});
		this.businessObjectDesList[restdaysIndex]["fvalue"] = "";
		setTimeout(() => {
			let sum: number = 0;
			this.leaveEntry.forEach((v: any) => {
			  console.log("v.qjts>>>>>>>", v.qjts);
			  if (v.qjts) {
          sum += parseFloat(v.qjts);
        }
			});
      console.log("sum>>>>>>", sum);
			let timeDiff: number = (new Date(endTime.replace(new RegExp("-","gm"),"/")).getTime() - new Date(startTime.replace(new RegExp("-","gm"),"/")).getTime()) / (1000 * 60 * 60 * 24);
			if (sum > Math.ceil(timeDiff)) {
				this.timeAlert("休假时间总和不能大于请假时间");
				this.leaveEntry.forEach((v: any) => {
					v.ksrq = startDateVal;
					v.kssj = "";
					v.jsrq = startDateVal;
					v.jssj = "";
					v.qjts = "";
				});
				this.businessObjectDesList[restdaysIndex]["fvalue"] = "";
			} else {
				this.businessObjectDesList[restdaysIndex]["fvalue"] = sum;
			}
		}, 2000);
      }
    }
  }

  /**
   * [loadData 初始化数据]
   */
  loadData() {
    var that = this;

    // 获得当前登录人ID
    this.storage.get('userInfo').then(function(userInfo) {
      if (userInfo) {
        that.loginid = userInfo.loginid;
      }
    });

    this.ops = this.navParams.get("ops");

    if (this.ops) {
      switch (this.ops) {
        case "update":
          this.taskDetail = this.navParams.get("taskDetail");//获取从流程详情页面传过来的业务对象
          if (this.taskDetail) {
            //获取到业务对象则是编辑流程信息
            _.forEach(this.taskDetail, detail => {
              if (detail["fvalue"] && detail["fvalue"]["changingThisBreaksApplicationSecurity"]) {
                detail["fvalue"] = detail["fvalue"]["changingThisBreaksApplicationSecurity"];
              }
            });
            this.bosid = this.navParams.get("bosid");//获取流程bosid
            this.initDetailDatas();
          }
          break;
        case "reject":
          this.bosid = this.navParams.get("bosid");//获取流程bosid
          this.initDetailDatas();
          break;
      }
    } else {
      this.ops = "insert";
    }

    this.detailService.getDetail(this.type, this.taskDetail, this.ops, this.bosid).then(function(data) {
      console.log("##draf.detail -> loadData()");
      console.log(data);
      //console.log(data);
      if (data && data["businessObjectDesList"] && data["workFlowParmeter"]) {
        that.flowParmeter = data["flowParmeter"];
        that.businessObjectDesList = data["businessObjectDesList"];
		that.workFlowParmeter = data["workFlowParmeter"];

        if (that.ops === "update") {
          let flowParams = that.navParams.get("flowParmeter");
          flowParams["nextNodeEditor"] = that.flowParmeter["nextNodeEditor"];
          flowParams["nextNodeEditorName"] = that.flowParmeter["nextNodeEditorName"];
          flowParams["nextNodesRadio"] = that.flowParmeter["nextNodesRadio"];
          flowParams["flowHandleType"] = 2;
          that.flowParmeter = flowParams;
        }

        if (that.ops != "insert") {
          that.updateWorkFlow();
          if (that.ops === "reject" && that.detailService.bomids[that.type] === "T_HR_GongWuWC") {
            that.initDefaltGwwcEmpByTree();
          }
        }

        if (that.ops === "reject" && that.type === "cjsq") {
          let chujingWhyField = _.find(that.businessObjectDesList, {"fieldid": "chujingWhy"});
          that.ionChange(chujingWhyField);
        }

        that.flowParmeter.nextNodeEditor = _.uniq(that.flowParmeter.nextNodeEditor);
        that.flowParmeter.nextNodeEditorName = _.uniq(that.flowParmeter.nextNodeEditorName);
        console.log(that.flowParmeter.nextNodeEditorName);

        // 初始化下一节点处理人
        if (that.workFlowParmeter.nextActivityDtos) {
          //初始化下一节点，下一节点默认选择人
          let firstNode = that.workFlowParmeter.nextActivityDtos[0];
          if (firstNode && firstNode.numb) {
            that.flowParmeter.nextNodesRadio = firstNode.numb; // 下一节点ID
            that.onNextNodeChange(firstNode.numb);
          }
        }

      }
    })

    this.detailService.getLeaveType().subscribe((data: any[]) => {
      this.leaveType = data;
    });
  }

  /**
   * 刷新流程节点信息
   */
  updateWorkFlow() {
    let that = this;
    switch (this.type) {
      case "ccsq":
        _.forEach(this.businessObjectDesList, bod => {
          if (bod["fieldid"] === "appConfirm") {
            bod["fvalue"] = "NO";
          }

          if (bod["fieldid"] === "dytype") {
            bod["isDisabled"] = true;
          }
        });
        break;
    }

    let entrys = this.detailService.formateBusinessObjectDes(this.businessObjectDesList);
    this.taskDetailService.updateBusinessObjectDes(this.bosid, entrys).subscribe(doResult => {
      if (doResult["code"] == "0") {
        this.storage.get("userInfo").then(user => {
          this.taskDetailService.getWorkFlowInfo(user, this.bosid,
            this.detailService.bomids[this.type]).subscribe(workFlowInfo => {
            console.log("getWorkFlowInfo", workFlowInfo);
            if (workFlowInfo) { // workFlowParmeter 不为空
              this.workFlowParmeter = workFlowInfo;
              _.forEach(_.keys(this.flowParmeter), function(key) {
                // 在workFlowParmeter中能匹配到值
                if (that.workFlowParmeter[key]) {
                  // 初始化flowParmeter值
                  that.flowParmeter[key] = that.workFlowParmeter[key];
                } else {
                  that.flowParmeter[key] = null;
                }
              });

              this.flowParmeter.nextNodeEditor = _.uniq(this.flowParmeter.nextNodeEditor);
              this.flowParmeter.nextNodeEditorName = _.uniq(this.flowParmeter.nextNodeEditorName);
              console.log(this.flowParmeter.nextNodeEditorName);

              // 初始化下一节点处理人
              if (this.workFlowParmeter.nextActivityDtos) {
                //初始化下一节点，下一节点默认选择人
                let firstNode = this.workFlowParmeter.nextActivityDtos[0];
                if (firstNode && firstNode.numb) {
                  this.flowParmeter.nextNodesRadio = firstNode.numb; // 下一节点ID
                  this.onNextNodeChange(firstNode.numb);
                }
              }
            }
          });
        });
      }
    });
  }

  initDefaltGwwcEmpByTree() {
    console.log("#########初始化组织树已选人员");
      this.storage.get("contact-user-list").then(u => {
        console.log(u);
        let outpeopleField = _.find(this.businessObjectDesList, {"fieldid": "outpeople"});
        if (outpeopleField && outpeopleField["fvalue"]) {
          let outpeopleEmpids = outpeopleField["fvalue"].split(",");
          console.log("outpeopleEmpids", outpeopleEmpids);
            _.forEach(outpeopleEmpids, empid => {
              let user = _.find(u, {"empid": empid});
              if (user) {
                let delfaultUser = {
                  empid: user["empid"],
                  loginid: user["loginid"],
                  name: user["emname"],
                  orgid: user["orgid"],
                  titleid: user["titleid"],
                  type: "user"
                };
                this.defaltGwwcEmpByTree.push(delfaultUser);
              }
            });
          console.log(this.defaltGwwcEmpByTree);
        }
      });
  }

  initDetailDatas() {
    switch (this.type) {
      case "ccsq":
        this.detailService.getChuChaiDetailData(this.bosid).subscribe(datas => {
          console.log("initDetailDatas返回");
          console.log(datas);
          if (datas) {
            _.forEach(datas, data => {
              let newEntry = {
                expand: true,
                selectedAddr: [],
                selectedCompanyCode: null,
                selectedIndustryInfo: [],
                field: new ChuchaiEntry()
              };
              newEntry.field = _.assignIn(newEntry.field, data["entry"]);
              this.detailEntry.push(newEntry);
            });
            console.log(this.detailEntry);
          }
        });
        break;
      case "cjsq":
        this.detailService.getChuJingDetailData(this.bosid).subscribe(datas => {
          if (datas) {
            _.forEach(datas, data => {
              let entry: any = {
                mxid: data["entry"]["mxid"],
                qjtype: data["entry"]["qjtype"],
                ksrq: data["entry"]["ksrq"],
                jsrq: data["entry"]["jsrq"],
                kssj: data["entry"]["kssj"],
                jssj: data["entry"]["jssj"],
                qjts: data["entry"]["qjts"],
                bzsm: data["entry"]["bzsm"],
                glbosid: data["entry"]["glbosid"]
              };
              this.leaveEntry.push(entry);
            });
          }
        });
        break;
    }
  }

  /**
   * [onNextNodeChange 选择下一节点,重新初始化下一节处理人]
   * @param {[type]} numb [下一节点ID]
   */
  onNextNodeChange(numb) {
    console.log("##下一节点ID：" + numb);
    this.empnames = [];
    this.empnamesId = [];
    this.flowParmeter.nextNodeEditorName = [];
    this.flowParmeter.nextNodeEditor = [];
    this.defaultEmpByTree = [];

    var node: any = _.find(this.workFlowParmeter.nextActivityDtos, { "numb": numb }); // 选择的节点
    if (node) {
      let participantDtos = node.participantDtos; // 人员节点

      _.forEach(node.participantDtos, participantDto => {
        if (!participantDto["empnames"]) {
          participantDto["empnames"] = [];
        }
        if (!participantDto["loginIds"]) {
          participantDto["loginIds"] = [];
        }
      });

      this.flowParmeter.flowCurrNode = node.nodeName; // 下一节点名称
      this.empnames = _.flattenDeep(_.map(node.participantDtos, "empnames")); // 人员数组
      this.empnamesId = _.flattenDeep(_.map(node.participantDtos, "loginIds")); // 人员ID数组

      // 获取有设置默认人员的节点 1：有，0：没有
      var fNode = _.filter(node.participantDtos, { "isDefault": 1 });
      // 没有设置默认人员节点并且第一个人员节点只有一个人，则选择第一个人员节点
      if(fNode.length == 0){
        if(participantDtos && participantDtos[0].empnames && participantDtos[0].empnames.length == 1) {
          fNode = _.concat(fNode,participantDtos[0]);
        }
      }

      if (fNode) {
        this.flowParmeter.nextNodeEditorName = _.flattenDeep(_.map(fNode, "empnames")); // 下一节点处理人
        this.flowParmeter.nextNodeEditor = _.flattenDeep(_.map(fNode, "loginIds")); // 下一节点处理人ID
      }
    }
  }

  /**
   * 选择下一节点处理人
   */
  chooseFlowEmp() {
    let that = this;
    let isRadio = true;
    // 有提供默认的选择人员时在默认人员肿选择，如果没有提供默人员则在组织树选择
    if (this.empnames.length > 0) {
      let modal = this.modalCtrl.create(EmpPage, {
        "isSelAddr": this.workFlowParmeter.isSelAddr,
        "empnames": this.empnames, "empnamesId": this.empnamesId,
        "defaultEmpnames": this.flowParmeter.nextNodeEditorName,
        "defaultEmpnamesId": this.flowParmeter.nextNodeEditor
      });
      modal.present();

      modal.onWillDismiss((data: any) => {
        if (data) {
          that.flowParmeter.nextNodeEditorName = data.defaultEmpnames;
          that.flowParmeter.nextNodeEditor = data.defaultEmpnamesId;
          //console.info("##返回的人员ID:" + that.defaultEmpnamesId);
        }
      });
    } else {
      let modal = this.modalCtrl.create(ContactChoosePage, {
        selected: this.defaultEmpByTree,
        isSelectUser: true
      });

      modal.present();
      modal.onWillDismiss((data: any[]) => {
        console.info(data);
        if (data) {
          that.defaultEmpByTree = data;
          that.flowParmeter.nextNodeEditorName = _.map(data, "name");
          that.flowParmeter.nextNodeEditor = _.map(data, "loginid"); // 外出人员用empid, 流程节点选择人用loginid
        }
      });
    }
  }


  /**
   * [checkIsSelected 控件显示隐藏开关]
   * @param {[type]} item [description]
   */
  checkIsSelected(item) {
    item.isShow = !item.isShow;
  }

  /**
   * 选择外出人员
   */
  chooseEmp(item) {
    console.log("##draft.detail.chooseEmpnames 选择外出人员");
    let that = this;
    let modal = this.modalCtrl.create(ContactChoosePage, {
      selected: this.defaltGwwcEmpByTree,
      isSelectUser: true
    });

    modal.present();
    modal.onWillDismiss((data: any[]) => {
      //console.info(data);
      if (data) {
        that.defaltGwwcEmpByTree = data;
        item["fvalue"] = _.toString(_.map(data, "empid")); // 外出人员用empid, 流程节点选择人用loginid
        item["fnameValue"] = _.toString(_.map(data, "name"));
      }
    });
  }


  /**
   * [ionChange 所有的下拉控件和日期空间，在选项发生改变时调用该方法,再根据feildid选择对应的处理的方法]
   * @param {[type]} item [节点，businessObjectDesList的元素]
   */
  ionChange(item) {
    //console.log("##draft.detail.ionChange");
    if (this.type == "ccsq") {
      switch (item["fieldid"]) {
        case "dytype":
          console.log(item);
          if (this.detailEntry && this.detailEntry.length > 0) {
            let alert = this.alertCtrl.create({
              title: "提示",
              message: "切换出差类型后将清空出差明细，请确认是否继续？",
              buttons: [{
                text: "取消",
                role: 'cancel',
                handler: () => {
                  item["fvalue"] = this.qyType;
                }
              }, {
                text: '确定',
                handler: () => {
                  this.detailEntry = [];
                  this.qyType = item["fvalue"];
                }
              }]
            });
            alert.present();
          } else {
            this.qyType = item["fvalue"];
          }
          break;
      }
    } else if (this.type == "cqbg") {

    } else if (this.type == "gwwc") {

    } else if (this.type == "qxjsq") {
      switch (item["fieldid"]) {
        case "startdate": // 起始日期
          this.detailService.calculateQJTX(item, this.businessObjectDesList, this.alertCtrl);
          break;
        case "startpoint": // 开始时间
          this.detailService.calculateQJTX(item, this.businessObjectDesList, this.alertCtrl);
          break;
        case "enddate": // 结束日期
          this.detailService.calculateQJTX(item, this.businessObjectDesList, this.alertCtrl);
          break;
        case "endpoint": // 结束时间
          this.detailService.calculateQJTX(item, this.businessObjectDesList, this.alertCtrl);
          break;
        case "resttype": // 休假类型
          this.detailService.calculateQJTX(item, this.businessObjectDesList, this.alertCtrl);
          this.detailService.resttypeChange(item, this.businessObjectDesList);
          break;
        case "isApplyTZXTQX":
          let isFundMgrField = _.find(this.businessObjectDesList, {"fieldid": "isFundMgr"});
          if (isFundMgrField) {
            isFundMgrField["fvalue"] = item["fvalue"];
            console.log("isFundMgrField", isFundMgrField);
          }
          break;
      }
    } else if (this.type === "cjsq") {
      //因公因私
      const forPublicPrivate: string[] = ["cdocation", "cjtype", "ccway", "ccreson", "resttel", "cjCation", "restdays", "restreson"];
      forPublicPrivate.forEach((v: string, i: number) => {
        let currIndex = _.findIndex(this.businessObjectDesList, {
          fieldid: v
        });
        if (v === "cjtype") {
          if (this.businessObjectDesList[currIndex]) {
            this.businessObjectDesList[currIndex]["fvalue"] = "2";
            this.businessObjectDesList[currIndex]["isDisabled"] = true;
          }
        }
        if (item.fieldid === "chujingWhy" && item.fvalue === "0") {
          if (this.businessObjectDesList[currIndex]) {
            i < 4 ? this.businessObjectDesList[currIndex]["isShow"] = true : this.businessObjectDesList[currIndex]["isShow"] = false;
            if (i >= 4) this.businessObjectDesList[currIndex]["fvalue"] = "";
            this.leaveEntry = [];
          }
        } else if (item.fieldid === "chujingWhy" && item.fvalue === "1") {
          if (this.businessObjectDesList[currIndex]) {
            i < 4 ? this.businessObjectDesList[currIndex]["isShow"] = false :
              this.businessObjectDesList[currIndex]["isShow"] = true;
            if (i < 4) this.businessObjectDesList[currIndex]["fvalue"] = "";
          }
        }
	  });
	  if (item["fieldid"] === "isApplyTZXTQX") {
		if (!_.find(this.businessObjectDesList, {
			fieldid: "isFundMgr"
		})) {
		    this.businessObjectDesList.push({
		        allowNull: true,
		        code: "0",
		        dataType: "BT01",
		        defaultListNum: 1,
		        defaultRowNum: 1,
		        desId: "string",
		        exception: "",
		        fieldid: "isFundMgr",
		        fname: "起草人是否基金经理",
		        fvalue: "YES",
		        fview: "YES",
		        isDisabled: false,
		        isShow: false,
		        msg: "成功！",
		        multiSelect: "NO",
		        pview: "YES",
		        refen: "[LOCATION]MAIN::[RULENUM]NULL::[NULL]YES::[COLSNUM]1::[ROWSNUM]1::[FIELDTYPE]NO::[ISMULTISELECT]NO::[PHONEVIEW]YES::[ISRELATION]NO",
		        refenDtos: [{
		            skey: "LOCATION",
		            svalue: "MAIN"
		        }, {
		            skey: "RULENUM",
		            svalue: "NULL"
		        }, {
		            skey: "NULL",
		            svalue: "YES"
		        }, {
		            skey: "COLSNUM",
		            svalue: "1"
		        }, {
		            skey: "ROWSNUM",
		            svalue: "1"
		        }, {
		            skey: "FIELDTYPE",
		            svalue: "NO"
		        }, {
		            skey: "ISMULTISELECT",
		            svalue: "NO"
		        }, {
		            skey: "PHONEVIEW",
		            svalue: "YES"
		        }, {
		            skey: "ISRELATION",
		            svalue: "NO"
		        }],
		        seque: 28,
		        type: "BT01"
		    });
		}
		console.log("基金经理", this.businessObjectDesList);
	  }
      //日期选择判断
      let startDateVal: string = _.find(this.businessObjectDesList, {
          fieldid: "startdate"
        })["fvalue"],
        startTimeVal: string = _.find(this.businessObjectDesList, {
          fieldid: "startpoint"
        })["fvalue"],
        endDateVal: string = _.find(this.businessObjectDesList, {
          fieldid: "enddate"
        })["fvalue"],
        endTimeVal: string = _.find(this.businessObjectDesList, {
          fieldid: "endpoint"
		})["fvalue"];
      let startTime = startDateVal + " " + startTimeVal + ":00",
        endTime = endDateVal + " " + endTimeVal + ":00";
      if ((item["fieldid"] === "startdate" || item["fieldid"] === "startpoint" || item["fieldid"] === "enddate" || item["fieldid"] === "endpoint") && this.leaveEntry.length > 0) {
        this.leaveEntry.forEach((v: any) => {
          v.ksrq = startDateVal;
          v.kssj = "";
          v.jsrq = startDateVal;
          v.jssj = "";
          v.qjts = "";
        });
        this.timeAlert("起始日期或结束日期已重置，请重新输入出境明细的时间段");
      }
      if (startTime > endTime) {
        let endDateIndex = _.findIndex(this.businessObjectDesList, {
            fieldid: "enddate"
          }),
          endTimeIndex = _.findIndex(this.businessObjectDesList, {
            fieldid: "endpoint"
          });
        setTimeout(() => {
          this.businessObjectDesList[endDateIndex]["fvalue"] = startDateVal;
          this.businessObjectDesList[endTimeIndex]["fvalue"] = "";
        }, 1000);
        this.timeAlert("结束时间不能小于起始时间");
	    }
    } else if (this.type === "xgipoxj") {
      if (item.fieldid == 'market') {
        let marketVal = item.fvalue;
        let SecuritiesCode = _.find(this.businessObjectDesList, {fieldid: "certiid"});
        if (marketVal === 'H') {
          this.ipoAssessPlaceholder = "标准：1-5分制";
        } else if (marketVal === 'S') {
          this.ipoAssessPlaceholder = "标准：6-100分制";
        } else {
          this.ipoAssessPlaceholder = "";
        }
        this.checkSecuritiesCode(SecuritiesCode, marketVal);
      }

    } else if (this.type === 'xgiposg') {
      if (item.fieldid == 'market') {
        console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>.asdasd', item )
        let marketVal = item.fvalue;
        let SecuritiesCode = _.find(this.businessObjectDesList, {fieldid: "CertiId"});
        this.checkSecuritiesCode(SecuritiesCode, marketVal);
      }
    }
  }

  /**
   * [submit 提交起草]
   */
  submit() {
    var that = this;
    let result = {
      code: "1",  // 1 校验通过； 0 校验不通过
      message: "" // 校验信息
    }

    // 出差申请:ccsq,出勤变更:cqbg,公务外出:gwwc,请休假申请:qxjsq
    // 提交校验
    switch (this.type) {
      case "ccsq":
        result = this.checkCCSQ();
        break;
      case "cqbg":
        result = this.checkNotNull();
        break;
      case "gwwc":
        result = this.checkGWWC();
        break;
      case "qxjsq":
        result = this.checkQXJSQ();
        break;
      case "cjsq":
        result = this.checkCJSQ();
        break;
      case "xgipoxj":
        result = this.checkXGIPOXJ();
        break;
      case "xgiposg":
        result = this.checkXGIPOSG();
        break;
    }

    // 校验有错误
    if (result.code == "0") {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: result.message,
        buttons: [
          {
            text: '确定',
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          }
        ]
      });
      alert.present();
    } else {

      if (this.type === "ccsq") {
        let treserved1Index = _.findIndex(this.businessObjectDesList, {fieldid: "treserved1"});
        let treserved2Index = _.findIndex(this.businessObjectDesList, {fieldid: "treserved2"});
        let startDateField = _.find(this.businessObjectDesList, {fieldid: "startdate"});
        let startpointField = _.find(this.businessObjectDesList, {fieldid: "startpoint"});
        let enddateField = _.find(this.businessObjectDesList, {fieldid: "enddate"});
        let endpointField = _.find(this.businessObjectDesList, {fieldid: "endpoint"});

        let temp_treserved1 = _.filter(this.businessObjectDesList, {fieldid: "treserved1"});
        if (temp_treserved1.length > 1) {
          _.remove(this.businessObjectDesList, this.businessObjectDesList[treserved1Index]);
          this.businessObjectDesList.push(temp_treserved1[0]);
          treserved2Index = _.findIndex(this.businessObjectDesList, {fieldid: "treserved1"});
        }

        let temp_treserved2 = _.filter(this.businessObjectDesList, {fieldid: "treserved2"});
        if (temp_treserved2.length > 1) {
          _.remove(this.businessObjectDesList, this.businessObjectDesList[treserved2Index]);
          this.businessObjectDesList.push(temp_treserved2[0]);
          treserved2Index = _.findIndex(this.businessObjectDesList, {fieldid: "treserved2"});
        }

        this.businessObjectDesList[treserved1Index]["fvalue"] = startDateField["fvalue"] + " " + startpointField["fvalue"] + ":00";
        this.businessObjectDesList[treserved2Index]["fvalue"] = enddateField["fvalue"] + " " + endpointField["fvalue"] + ":00";
        console.log("treserved1Index", this.businessObjectDesList);
      }

      let nextNode = _.find(this.workFlowParmeter.nextActivityDtos, {numb: this.flowParmeter.nextNodesRadio});
      let message = "您确定要提交文件到'" + nextNode["nodeName"] + "'" + "节点并交给'" + this.flowParmeter.nextNodeEditorName + "'进行处理吗？";
      let alert = this.alertCtrl.create({
        title: "提示",
        message: message,
        buttons: [
          {
            text: "取消",
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          }, {
            text: '确定',
            handler: () => {
              this.insert(); // 插入起草信息
            }
          }
        ]
      });
      alert.present();
    }

  }

  /**
   * [insert 插入起草信息]
   */
  insert() {
    var that = this;
    this.flowParmeter.flowHandleType = "02"; // 提交默认为"02"
    this.flowParmeter.flowAppointNodeSel = null; // 驳回的节点
    this.flowParmeter.flowCountermandNotion = ""; // TODO : 驳回意见, 目前都是用flowNotion来接收各类意见，是否需要分开？
    //--意见附加  根据朱文达微信端的逻辑写的
    this.flowParmeter.flowOldNotion = this.flowParmeter.flowOldNotion ? this.flowParmeter.flowOldNotion : "";
    if (this.flowParmeter.flownotioninputstyle && this.flowParmeter.flownotioninputstyle == 2) {
      this.flowParmeter.flowOldNotion = "";
    }
    this.flowParmeter.isOther = false;
    this.flowParmeter.bostitle = _.find(this.businessObjectDesList, { "fieldid": "bostitle" })["fvalue"];
    this.flowParmeter.clientType = this.common.getClientType();
    //this.flowParmeter.bid = id;
    this.flowParmeter.bomid = this.detailService.bomids[this.type]
    this.flowParmeter.loginId = this.loginid;
    this.flowParmeter.authLoginId = this.loginid; // 起草人ID,因为是当前登录人起草所以用loginid
    /*
     <<<<<<< HEAD
     this.detailService.insertDetail(this.businessObjectDesList, this.flowParmeter, this.detailEntry, this.leaveEntry).then(function(result) {
     =======*/
    this.detailService.insertDetail(this.businessObjectDesList, this.flowParmeter, this.detailEntry, this.leaveEntry, this.ops, this.bosid).then(function(result) {
// >>>>>>> d0dd4def41a44c87c4c64a6af4c2d5e463dcd939
      console.log(result);
      if (result["code"] == "1") {
        if (that.ops != "insert") {//不是起草流程时
          that.events.publish("task-detail:toBeDeal,todo,deal has updated", {"bid": that.bosid});
          that.events.publish("task-detail:todo,deal has updated", {"bid": that.bosid});
          that.navCtrl.popToRoot();
        } else {
          that.navCtrl.pop();
        }
        //that.navCtrl.push(DraftListPage); // 提交成功，跳转到列表页面
        console.log("##draft.detail.insert 起草插入成功");
      } else {
        let alert = that.alertCtrl.create({ // 有异常信息，弹出提示
          title: "异常信息提示",
          message: result["msg"],
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                //console.log('Cancel clicked');
              }
            }
          ]
        });
        alert.present();
      }
    });
  }


  /**
   * [checkNotNull 校验非空字段]
   * 返回：{"code","message"} code :1 校验通过； 0 校验不通过; message 异常信息
   */
  checkNotNull() {
    console.log("##draft.detail.checkNotNull 提交校验非空字段");
    let result = {
      code: "1",  // 1 校验通过； 0 校验不通过
      message: "" // 校验信息
    }
    var that = this;
    // 只对界面上显示的字段校验非空
    var nodes: any = _.filter(this.businessObjectDesList, { "isShow": true });

    // 将流程审批操作加入非空校验，必须构建对象{"allowNull":,"fname","fvalue"}
    nodes = _.union(nodes, [{
        "allowNull": false,
        "fname": "下一处理节点",
        "fvalue": this.flowParmeter.nextNodesRadio  //下一节点ID
      }, {
        "allowNull": false,
        "fname": "下一节点处理人",
        "fvalue": _.toString(this.flowParmeter.nextNodeEditor)
      }]
    );

    for (var i = 0; i < nodes.length; i++) {
      //console.log(nodes[i]["allowNull"] + nodes[i]["fvalue"]);
      if (nodes[i]["allowNull"] == false && _.trim(nodes[i]["fvalue"]) == "") {
        result.code = "0";
        result.message = "'" + nodes[i]["fname"] + "'不能为空";
        break;
      }
    };

    return result;
  }



  /**
   * [checkQXJSQ 请休假提交校验]
   * 返回：{"code","message"} code :1 校验通过； 0 校验不通过; message 异常信息
   */
  checkQXJSQ() {
    let result = {
      code: "1",  // 1 校验通过； 0 校验不通过
      message: "" // 校验信息
    }

    result = this.checkNotNull();
    if (result.code == "1") {
      let node = _.find(this.businessObjectDesList, { "fieldid": "restdays" });
      // 根据
      if (node["fvalue"] <= 0) {
        result.code = "0";
        result.message = "请休假的结束时间必须大于开始时间";
      } else {
        let resttype_node = _.find(this.businessObjectDesList, {"fieldid": "resttype"});
        let yearRest = _.find(resttype_node["fieldvalDtos"], {fdval: "年休假"});
        if (resttype_node["fvalue"] === yearRest["fvau"]) {
          let startdate_node = _.find(this.businessObjectDesList, {"fieldid": "startdate"});
          let startpoint_node = _.find(this.businessObjectDesList, {"fieldid": "startpoint"});
          let enddate_node = _.find(this.businessObjectDesList, {"fieldid": "enddate"});
          let endpoint_node = _.find(this.businessObjectDesList, {"fieldid": "endpoint"});
          if (parseInt(enddate_node["fvalue"].substr(0, 4)) >
            parseInt(startdate_node["fvalue"].substr(0, 4))) {

          } else {
            let ext_nxjxx_node = _.find(this.businessObjectDesList, {"fieldid": "ext-nxjxx"});
            let tzhkxDays = _.find(ext_nxjxx_node["fvalue"], {numb: "tzhkxDays"});
            if (parseFloat(tzhkxDays["fvau"]) < node["fvalue"]) {
              result.code = "0";
              result.message = "申请的今年年假的休假天数超出了“今年调整后剩余可休假天数”，请重新填写休假时间！"
            }
          }
        }
      }

    }

    return result;
  }

  /**
   * [checkCCSQ 出差申请提交校验]
   * 返回：{"code","message"} code :1 校验通过； 0 校验不通过; message 异常信息
   */
  checkCCSQ() {
    let result = {
      code: "1",  // 1 校验通过； 0 校验不通过
      message: "" // 校验信息
    }

    result = this.checkNotNull();

    if (result.code == "1") {
      let retVal = this.detailService.checkStartEndTime(this.businessObjectDesList);
      if(!retVal){
        result.code = "0";
        result.message = "出差申请的结束时间必须大于开始时间";
      }
      this.detailService.setIsFundMgr(this.businessObjectDesList);
    }

    if (this.detailEntry && this.detailEntry.length > 0) {
      let isNull = _.filter(this.detailEntry, entry => {
        let compareResult = false;
        switch (this.qyType) {
          case "1":
            switch (entry.field.rescatg) {
              case "1":
                if (!entry.field.gscode) {
                  compareResult = true;
                } else {
                  if (!entry.field.address) {
                    compareResult = true;
                  } else {
                    if (!entry.field.remark) {
                      compareResult = true;
                    }
                  }
                }
                break;
              case "2":
                if (!entry.field.indinf) {
                  compareResult = true;
                } else {
                  if (!entry.field.address) {
                    compareResult = true;
                  } else {
                    if (!entry.field.remark) {
                      compareResult = true;
                    }
                  }
                }
                break;
              case "3":
                if (!entry.field.address) {
                  compareResult = true;
                } else {
                  if (!entry.field.remark) {
                    compareResult = true;
                  }
                }
                break;
            }
            break;
          case "2":
            if (!entry.field.address) {
              compareResult = true;
            } else {
              if (!entry.field.remark) {
                compareResult = true;
              }
            }
            break;
        }
        return compareResult;
      });

      if (isNull && isNull.length > 0) {
        result.code = "0";
        result.message = "出差明细中存在未填写信息";
      }
    } else {
      if (this.qyType == "1") {
        result.code = "0";
        result.message = "出差类型为调研时必须添加出差明细";
      }
    }

    return result;
  }

  /**
   * [checkGWWC 出差申请提交校验]
   * 返回：{"code","message"} code :1 校验通过； 0 校验不通过; message 异常信息
   */
  checkGWWC() {
    let result = {
      code: "1",  // 1 校验通过； 0 校验不通过
      message: "" // 校验信息
    }

    result = this.checkNotNull();

    if (result.code == "1") {
      let retVal = this.detailService.checkStartEndTime(this.businessObjectDesList);
      if(!retVal){
        result.code = "0";
        result.message = "公务外出的结束时间必须大于开始时间";
      }

    }

    return result;
  }

  /**
   * [checkCJSQ 出境申请提交校验]
   * 返回：{"code","message"} code :1 校验通过； 0 校验不通过; message 异常信息
   */
  checkCJSQ() {
    let result: any = {
      code: "1", //0表示校验不通过，1表示校验通过
      message: "" //校验信息
    };
    result = this.checkNotNull();
    if (result.code === "1") {
      let retVal = this.detailService.checkStartEndTime(this.businessObjectDesList);
      if (!retVal) {
        result.code = "0";
        result.message = "结束时间必须大于开始时间";
      }
    }
    let whyIndex = _.findIndex(this.businessObjectDesList, {
      fieldid: "chujingWhy"
    });
    if (result.code === "1") {
      const forPublic: string[] = ["cdocation", "ccway", "ccreson"],
        forPrivate: string[] = ["resttel", "cjCation", "restreson"];
      if (this.businessObjectDesList[whyIndex]["fvalue"] === "0") {
        for (let i: number = 0; i < forPublic.length; i++) {
          let fieldIndex =  _.findIndex(this.businessObjectDesList, {
            fieldid: forPublic[i]
          });
          if (this.businessObjectDesList[fieldIndex]["fvalue"] == "") {
            result.code = 0;
            result.message = this.businessObjectDesList[fieldIndex]["fname"] + "不能为空";
            break;
          }
        }
      } else if (this.businessObjectDesList[whyIndex]["fvalue"] === "1") {
        for (let i: number = 0; i < forPrivate.length; i++) {
          let fieldIndex =  _.findIndex(this.businessObjectDesList, {
            fieldid: forPrivate[i]
          });
          if (this.businessObjectDesList[fieldIndex]["fvalue"] == "") {
            result.code = 0;
            result.message = this.businessObjectDesList[fieldIndex]["fname"] + "不能为空";
            break;
          }
        }
      }
    }
    if (result.code === "1" && this.businessObjectDesList[whyIndex]["fvalue"] === "1") {
      if (this.leaveEntry.length > 0) {
        for (let i: number = 0; i < this.leaveEntry.length; i++) {
          if (this.leaveEntry[i].qjtype === "") {
            result.code = 0;
            result.message = "出境明细的请假类型不能为空";
            break;
          }
          if (this.leaveEntry[i].kssj === "" || this.leaveEntry[i].jssj === "") {
            result.code = 0;
            result.message = "出境明细的时间节点不能为空";
            break;
          }
        }
      } else {
        result.code = 0;
        result.message = "出境明细不能为空";
      }
    }
    return result;
  }

  /**
   * [checkXGIPOXJ 新股IPO询价校验]
   * 返回：{"code","message"} code :1 校验通过； 0 校验不通过; message 异常信息
   */
  checkXGIPOXJ() {

    let result: any = {
      code: "1", //0表示校验不通过，1表示校验通过
      message: "" //校验信息
    };

    result = this.checkNotNull();
    return result;
  }

  /**
   * [checkXGIPOXJ 新股IPO网上申购校验]
   * 返回：{"code","message"} code :1 校验通过； 0 校验不通过; message 异常信息
   */
  checkXGIPOSG() {
    console.log(this.businessObjectDesList)

    let result: any = {
      code: "1", //0表示校验不通过，1表示校验通过
      message: "" //校验信息
    };

    result = this.checkNotNull();

    if (result.code === "1" ) {
      let isReview: any = _.find(this.businessObjectDesList, {fieldid: "iszqfh"})["fvalue"];
      if (!isReview) {
        result.code = 0;
        result.message = "请点击复核证券信息后再次提交";
      }
    }
    return result;
  }

  /**
   * [addBGMX 添加变更明细]
   * @param {[type]} item [description]
   */
  addBGMX(item) {
    this.detailService.addBGMX(item, this.businessObjectDesList);
  }

  /**
   * [deleteBGMXNode 删除变更明细]
   * @param {[type]} item [description]
   * @param {[type]} i    [description]
   */
  deleteBGMXNode(item, i) {
    this.detailService.deleteBGMXNode(item, i, this.businessObjectDesList);
  }

  /**
   * [bgmxChange 变更明细有修改，更新明细信息]
   * @param {[type]} item [description]
   */
  bgmxChange(item) {
    this.detailService.bgmxChange(item, this.businessObjectDesList);
  }

  /**
   * [ipoDetailData 根据证券代码，获取信息]
   * @param {[number]} value [证券代码]
   */
  ipoDetailData(item) {
    let marketVal: string = _.find(this.businessObjectDesList, {fieldid: "market"})["fvalue"];
    this.checkSecuritiesCode(item, marketVal);
  }

  /**
   * [checkAssess 新股IPO询价评价校验]
   * @param {[type]} value [description]
   */
  checkAssess(item) {
    let marketVal: string = _.find(this.businessObjectDesList, {fieldid: "market"})["fvalue"];

    if (marketVal === 'H' && item.fvalue > 5) {
      item.fvalue = 5;
    }else if (marketVal === 'H' && item.fvalue < 1) {
      item.fvalue = '';
    }

    if (marketVal === 'S' && item.fvalue > 100) {
      item.fvalue = item.fvalue.slice(0, 2);
    }else if (marketVal === 'S' && item.fvalue < 6) {
      item.fvalue = '';
    }
  }

  /**
   * [checkSecuritiesCode 市场和证券代码的校验]
   * @param {[type]} item [description]
   * @param {[type]} marketVal [description]
   */
  checkSecuritiesCode(item, marketVal) {
    let value = item.fvalue

    if (/^[0,3,6]\d{5}$/.test(value)) {
      this.detailService.getUnderwriter(item, this.businessObjectDesList)
    }

    if (value && marketVal){
      if (marketVal == 'H'){
        if (!/^6/.test(value)) {
          let alert = this.alertCtrl.create({
            title: "提示",
            message: '所属市场为上海，上海市场必须以“6”开头',
            buttons: [
              {
                text: '确定',
                role: 'cancel',
                handler: () => {}
              }
            ]
          });
          alert.present();
          item.fvalue = '';
          return
        }
      }else if (marketVal == 'S') {
        if(!/^0|^3/.test(value)) {
          let alert = this.alertCtrl.create({
            title: "提示",
            message: '所属市场为深圳，深圳市场必须以“0”或3开头',
            buttons: [
              {
                text: '确定',
                role: 'cancel',
                handler: () => {}
              }
            ]
          });
          alert.present();
          item.fvalue = '';
          return
        }
      }

      this.detailService.ipoDetailData(value, marketVal, this.businessObjectDesList)
    }
  }

  /**
   * [infoReview 证券信息复核]
   * @param {[type]} item [description]
   */
  infoReview(item) {

    /*let result: any = {
      code: "1", //0表示校验不通过，1表示校验通过
      message: "" //校验信息
    };
    result = this.checkNotNull();
    if (result.code == "0") {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: result.message,
        buttons: [
          {
            text: '确定',
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          }
        ]
      });
      alert.present();
      return false;
    }*/

    let confirm = this.alertCtrl.create({
      title: '提示',
      message: '确定证券信息已复核？',
      buttons: [
          {
            text: '取消',
            handler: () => {
                console.log('Disagree clicked');
            }
          },
          {
            text: '确定',
            handler: () => {
              item["isDisabled"] = true;
              let isReview: any = _.find(this.businessObjectDesList, {fieldid: "iszqfh"})["fvalue"] = "Y";
            }
          }
      ]
    });
    confirm.present();
  }

  /**
   * [autoTitle 询价/申购标题补全, 申购代码补全]
   * @param {[type]} item [description]
   */
  autoTitle(item) {
    let title: string = _.find(this.businessObjectDesList, {fieldid: "bostitle"})["fvalue"];
    let nowData: string = _.replace(this.common.getNowFormatDate(), /-/g, '')
    let newTitle: string = nowData + '-' + item['fvalue'];
    if (this.type === 'xgipoxj') {
      _.find(this.businessObjectDesList, {fieldid: "bostitle"})["fvalue"] = newTitle + '新股询价';
    } else if (this.type === 'xgiposg') {
      _.find(this.businessObjectDesList, {fieldid: "bostitle"})["fvalue"] = newTitle + '网上申购';
      let marketVal: string = _.find(this.businessObjectDesList, {fieldid: "market"})["fvalue"];
      if(marketVal === 'S') {
        _.find(this.businessObjectDesList, {fieldid: "sgnum"})["fvalue"] = item['fvalue'];
      }
    }
  }
}
